package com.btm.distrb.service;

import com.btm.distrb.config.MysqlConfig;
import com.btm.distrb.detection.TableDetection;
import com.btm.distrb.model.DBInfo;
import com.btm.distrb.model.Table;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class Detection {

    private String[] prefix = null;

    public Detection(String... prefix){
        this.prefix = prefix;
    }

    public Map<String,Table> standardDB(String url,String userName,String password,String catalog){
        MysqlConfig mysqlConfig = new MysqlConfig();
        mysqlConfig.setUrl(url);
        mysqlConfig.setUserName(userName);
        mysqlConfig.setPassword(password);
        Connection connection = null;
        Map<String,Table> standard = null;
        try {
            connection = mysqlConfig.getConnection();
            TableDetection tableDetection = new TableDetection(connection);
            standard = tableDetection.getAllTableAndColumn(catalog,standard,prefix);
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            if (null != connection){
                try{
                    connection.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }
        }
        return standard;
    }

    public void detectionDB(DBInfo[] dbInfos,Map<String,Table> map){
        for (DBInfo dbinfo :
                dbInfos) {
            MysqlConfig mysqlConfig = new MysqlConfig();
            mysqlConfig.setUrl(dbinfo.getUrl());
            mysqlConfig.setUserName(dbinfo.getUserName());
            mysqlConfig.setPassword(dbinfo.getPassword());
            Connection connection = null;
            try{
                connection = mysqlConfig.getConnection();
                TableDetection tableDetection = new TableDetection(connection);
                tableDetection.getAllTableAndColumn(dbinfo.getCatalog(),map,prefix);
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
    }

}
